<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示信息区域 -->
      <el-alert title="添加商品信息" type="info" show-icon :closable="false"></el-alert>
      <!-- 步骤条区域  -0可以把字符串转化为数字(索引)-->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单放最外面，才会把所有选项里面的数据收集到一起 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="catelist" :props="cateProps"
              @change="handleChange" clearable>
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyTableData" :key='item.attr_id' :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-form-item label="商品分类">
              <!-- action：图片要上传的api地址 -->
              <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove"
              list-type="picture" :headers="headerObj" :on-success="handleSuccess">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器插件使用 -->
            <quill-editor v-model="addForm.goods_introduce" ref=""></quill-editor>
            <!-- :options="" @blur="" @focus="" @ready="" -->
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt="" width="100%">
    </el-dialog>
  </div>
</template>

<script>
// 导入深拷贝插件
import _ from 'lodash'
import { Form } from 'element-ui'

export default {
  data () {
    return {
      // 步骤条步骤索引(标签页索引)
      activeIndex: '0',
      // Tab标签页方向
      tabPosition: 'left',
      // 添加商品数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        // 上传的图片路径数组
        pics: [],
        // 商品详情描述
        goods_introduce: '',
        // 参数属性数组
        attrs: []
      },
      // 添加商品表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类参数列表数据
      catelist: [],
      // 级联选择器配置选项
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 当前选中分类商品动态参数
      manyTableData: [],
      // 当前选中商品静态属性
      onlyTableData: [],
      // 上传图片的url地址； 注意：图片上传的地址并不是前端路由地址，而是后端根地址+path
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的headers请求头对象,请求头中添加token,因为upload自带的异步请求没有设置token
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 获取图片预览地址，可以直接点击的地址，不是临时地址
      previewPath: '',
      // 图片预览框的显示与隐藏
      previewVisible: false
    }
  },
  computed: {
    // 选中商品分类的id
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      // 如果不是三级则没有id，为空
      return null
    }
  },
  methods: {
    // 获取参数分类列表
    async getCateList() {
      const { data: res } = await this.axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类参数列表失败！')
      this.catelist = res.data
    },
    // 级联选择器选中项变化，触发函数
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 切换Tabs标签触发函数
    beforeTabLeave (activeName, oldName) {
      // 没有选择商品分类则无法向下点击
      if (oldName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类!')
        return falseId
      }
    },
    // tab标签被选中时触发，就可以获取当前选中项的索引
    async tabClicked () {
      // 当选中项为1时，请求商品动态参数数据
      if (this.activeIndex === '1') {
        const { data: res } = await this.axios.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error('获取商品动态参数失败!')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.axios.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error('获取商品静态属性失败!')
        this.onlyTableData = res.data
        console.log(res.data)
      } else if (this.activeIndex === '3') {

      }
    },
    // 处理图片预览效果
    handlePreview (file) {
      this.previewPath = file.response.data.url
      // 显示预览对话框
      this.previewVisible = true
    },
    // 处理移除图片的操作
    handleRemove (file) {
      // 找到临时地址······················
      const filePath = file.response.data.tmp_path
      // 找到在数组中的索引
      const i = this.addForm.pics.findIndex(item => item.pic === filePath)
      // 在数组中移除
      this.addForm.pics.splice(i, 1)
    },
    // 监听图片上传成功的事件
    handleSuccess(res) {
      // 先满足数据需要的格式，再添加进addForm表单对象中，统一处理
      const picInfo = { pic: res.data.tmp_path }
      this.addForm.pics.push(picInfo)
    },
    // 添加商品
    add () {
      this.$refs.addFormRef.validate(async valid => {
        // 表单预验证
        if (!valid) return this.$message.error('请填写必要的表单项！')
        // 通过验证，执行添加逻辑
        // 把提交数据变成正确的格式，不能直接变化原本数据的格式，或导致出错，所以深拷贝再改变格式
        // 利用lodash插件，深拷贝cloneDeep()
        const cloneForm = _.cloneDeep(this.addForm)
        cloneForm.goods_cat = cloneForm.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          this.addForm.attrs.push(newInfo)
        })
        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        cloneForm.attrs = this.addForm.attrs
        // 发起请求
        const { data: res } = await this.axios.post('goods', cloneForm)
        if (res.meta.status !== 201) this.$message.error('添加商品失败!')
        this.$message.success('添加商品成功!')
        this.$router.push('/goods')
      })
    }
  },
  created () {
    this.getCateList()
  },
  components: {}
}
</script>

<style lang="scss" scoped>
.el-alert{
  display: flex;
  justify-content: center;
}
.el-checkbox{
  margin: 0;
}
.btnAdd{
  margin-top: 15px;
}
</style>
